package org.eirudy.shareimage.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.eirudy.shareimage.constant.UserConstant;
import org.eirudy.shareimage.manager.auth.StpKit;
import org.eirudy.shareimage.model.dto.user.UserQueryRequest;
import org.eirudy.shareimage.model.entity.User;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.eirudy.shareimage.exception.BusinessException;
import org.eirudy.shareimage.exception.ErrorCode;
import org.eirudy.shareimage.exception.ThrowUtils;
import org.eirudy.shareimage.model.enums.UserRoleEnum;
import org.eirudy.shareimage.model.vo.LoginUserVO;
import org.eirudy.shareimage.model.vo.UserVO;
import org.eirudy.shareimage.service.UserService;
import org.eirudy.shareimage.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Eirudy
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-05-07 08:47:25
*/

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{


    /**
     *
     * @param userAccount 账户
     * @param userPassword 密码
     * @param checkPassword 确认密码
     * @return
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 检查参数
            if(StrUtil.hasBlank(userAccount, userPassword, checkPassword)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
            }

            if(userAccount.length() < 4){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户过短");
            }

            if(!userPassword.equals(checkPassword)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不一致");
            }

        // 2. 检查数据库中是否中已有重复

            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);

            long count = this.baseMapper.selectCount(queryWrapper);
            if(count > 0){
                throw  new BusinessException(ErrorCode.PARAMS_ERROR,"账号已存在");
            }
        // 3. 密码加密
            String encryptPassword = getEncryptPassword(userPassword);
        // 4. 存入数据库
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("no_name");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult,ErrorCode.SYSTEM_ERROR,"添加失败，数据库错误");

        return user.getId();
    }



    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.一些基本错误，比如账户过短
            ThrowUtils.throwIf(userAccount.length() < 4,ErrorCode.PARAMS_ERROR,"账户过短");



        //2. 获得加密密码
        String encryptPassword = this.getEncryptPassword(userPassword);
        //3.查询数据库是否有该用户 直接用户不存在或者密码错误
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        if(user == null){
            log.info("user login failed");
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"用户不存在或者密码错误");
        }

        //4.记录登录态
        HttpSession session = request.getSession();
        session.setAttribute(UserConstant.USER_LOG_IN_STATE,user);

        // 记录用户登录信息到Sa-token
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(UserConstant.USER_LOG_IN_STATE,user);

        //5. 返回脱敏后的类
        return getLoginUserVO(user);
    }


    /**
     *
     * @param password
     * @return 加密后的密码
     */
    @Override
    public String getEncryptPassword(String password) {
        final String salt = "Eirudy";
        return DigestUtils.md5DigestAsHex((salt+password).getBytes());
    }

    public LoginUserVO getLoginUserVO(User user){
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user,loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        UserVO UserVO = new UserVO();
        BeanUtil.copyProperties(user,UserVO);
        return UserVO;
    }

    /**
     * 获取脱敏后的用户列表
     * @param users
     * @return
     */
    @Override
    public List<UserVO> getUserVOList(List<User> users) {
        if(CollUtil.isEmpty(users)){
            return new ArrayList<UserVO>();
        }
        return users.stream()
                .map(this::getUserVO)
        .collect(Collectors.toList());
    }

    /**
     *
     * @param request
     * @return 该函数用于内部使用。
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        //判断是否已经登录
        Object object = request.getSession().getAttribute(UserConstant.USER_LOG_IN_STATE);
        User currentuser = (User) object;

        if(currentuser == null || currentuser.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        //防止在业务处理期间修改了某些操作
        Long id = currentuser.getId();
        currentuser = this.getById(id);
        ThrowUtils.throwIf(currentuser == null,ErrorCode.NOT_LOGIN_ERROR);
        return currentuser;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        //1. 通过request获得session
        //2.判断有无login_state,如果有，修改，没有，直接抛出
        HttpSession session = request.getSession();
        Object object = session.getAttribute(UserConstant.USER_LOG_IN_STATE);

        ThrowUtils.throwIf(object == null,ErrorCode.OPERATION_ERROR,"未登录");


        // 删除登录态
        session.removeAttribute(UserConstant.USER_LOG_IN_STATE);
        StpKit.SPACE.logout(((User) object).getId());
        //StpKit.SPACE.getSession().delete(UserConstant.USER_LOG_IN_STATE);


        return true;
    }

    /**
     *  封装QueryWrapper
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userRole = userQueryRequest.getUserRole();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);

        return queryWrapper;
    }

    @Override
    public boolean isAdmin(User user) {
        if (user == null) {
            return false;
        }
        return user.getUserRole().equals(UserRoleEnum.ADMIN.getValue());
    }
}




